/**
 * 防抖函数
 * @param fn 需要执行的函数
 * @param delay 延迟执行时间（毫秒）
 * @param immediate 是否立即执行
 */
export function debounce(fn: Function, wait = 200, immediate = true) {
  let timer: any = null
  return function anonymouse(this: any) {
    // eslint-disable-next-line prefer-rest-params
    const args = arguments
    if (timer) clearTimeout(timer)
    const now = immediate && !timer
    timer = setTimeout(() => {
      timer = null
      !immediate && fn.apply(this, args)
      // fn.apply(this, args)
    }, wait)
    now && fn.apply(this, args)
  }
}

export default {
  install(Vue: any) {
    Vue.mixin({
      directives: {
        loadmore: {
          bind(el: any, binding: any) {
            let bindTime: any = null
            clearTimeout(bindTime)
            // let selectWrap = el
            bindTime = window.setTimeout(function () {
              let selectWrap = el
              const container = el.getAttribute('scrollContainer')
              if (container) selectWrap = document.querySelector(container)
              let lastScrollTop = 0
              const offsetValue = el.getAttribute('offsetValue') || 20
              binding.value = debounce(binding.value, 1000)
              selectWrap.addEventListener('scroll', function (this: any) {
                if (this.scrollTop === 0) {
                  binding.value('up', this)
                  return false
                }
                if (lastScrollTop !== (this as any).scrollTop) {
                  lastScrollTop = this.scrollTop
                  const scrollDistance = this.scrollHeight - this.scrollTop - this.clientHeight
                  if (scrollDistance <= offsetValue) {
                    binding.value('down', this)
                  }
                }
              }, false)
            }, 200)
          }
        }
      }
    })
  }
}
